<template>
  <div class="home">
    <!--  左侧  -->
    <div class="item item-left">
      {{ activeIndex }}
    </div>

    <!--  中间  -->
    <div class="content">
      <el-input
          class="input"
          placeholder="标题"
          maxlength="60"
          show-word-limit v-model="title"
          size="large">
      </el-input>
      <div>
        <vue-ueditor-wrap
            v-model="msg"
            :config="editorConfig"
            editor-id="editor-demo-01"
            @ready="onEditorReady"
            class="ueditor">
        </vue-ueditor-wrap>
        <p style="border-bottom: 1px solid #f2f2f2;margin-bottom: 10px;"></p>
        <p style="margin-bottom: 10px;">封面和摘要</p>

        <div class="thumb-desc">
          <el-dropdown>
            <span class="el-dropdown-link">
                <div class="thumb-con">
                    <i class="el-icon-plus" v-if="!result"></i>
                    <img :src="result" class="thumb-img" v-else alt="">
                </div>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-upload
                      class="upload-con"
                      action="#"
                      :show-file-list="false"
                      :on-change="beforeUpload"
                      :auto-upload="false">
                    <template #default>
                      <div style="width: 90px;text-align: center;">上传</div>
                    </template>
                  </el-upload>
                </el-dropdown-item>
                <el-dropdown-item>
                  图片库中选择
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <div class="desc">
            <el-input
                type="textarea"
                resize="none"
                :rows="4"
                placeholder="请输入内容简介，不写默认抓取内容前54个字"
                v-model="desc">
            </el-input>
          </div>
        </div>
      </div>
      <div class="btn-con">
        <div class="con">
          <el-button class="preview" @click="saveToLocal" size="mini">保存到本地</el-button>
          <el-button class="preview" @click="preview" size="mini">预 览</el-button>
          <el-button type="primary" class="preview" @click="massMailing" size="mini">保存并群发</el-button>
        </div>
      </div>
    </div>

    <!--  右侧  -->
    <div class="item item-left">
      <div>
        <el-menu
            default-active="1"
            background-color="#f5f5f5"
            class="el-menu-vertical-demo">
          <el-menu-item index="1" @click="activeIndex=1;">
            <i class="el-icon-menu"></i>
            <template #title>图文消息</template>
          </el-menu-item>
          <el-menu-item index="2" @click="activeIndex=2;">
            <i class="el-icon-document"></i>
            <template #title>模板消息</template>
          </el-menu-item>

        </el-menu>
      </div>

    </div>

  </div>
  <div>

  </div>
  <!-- 小程序弹窗 -->
  <el-dialog
      title="插入小程序"
      :show-close="false"
      :close-on-click-modal="false"
      v-model="dialogVisible"
      width="500px">

    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item label="展示方式">
        <el-radio-group v-model="type">
          <el-radio :label="1">文字</el-radio>
          <el-radio :label="2">图片</el-radio>
          <!--<el-radio :label="3">小程序卡片</el-radio>-->
        </el-radio-group>
      </el-form-item>

      <el-form-item label="小程序路径">
        <el-input v-model="path" size="small" placeholder="小程序路径"></el-input>
      </el-form-item>

      <el-form-item label="小程序AppId">
        <el-input v-model="appId" size="small" placeholder="小程序AppId"></el-input>
      </el-form-item>

      <el-form-item label="文字内容" v-if="type===1">
        <el-input v-model="content" size="small" placeholder="文字内容"></el-input>
      </el-form-item>

    </el-form>

    <template #footer>
    <span class="dialog-footer">
      <el-button size="small" @click="dialogVisible = false">取 消</el-button>
      <el-button size="small" type="primary" @click="insertApplets">插 入</el-button>
    </span>
    </template>
  </el-dialog>

  <!-- 图片裁剪 -->
  <el-dialog v-model="isShowDialog" width="700px" title="图片裁切">
    <vue-picture-cropper
        :boxStyle="{
          width: '100%',
          height: '100%',
          backgroundColor: '#f8f8f8',
          margin: 'auto'
        }"
        :img="pic"
        :options="options"
        @ready="ready"/>
    <template #footer>
      <el-button @click="isShowDialog = false;">取消</el-button>
      <el-button @click="clear">清除</el-button>
      <el-button @click="reset">重置</el-button>
      <el-button type="primary" @click="getResult">裁切</el-button>
    </template>

  </el-dialog>

  <!-- 上传图片 -->
  <el-dialog
      v-model="addImageDialog"
      :show-close="false"
      title="图片选择"
      :close-on-click-modal="false">

    <template #default>

      <el-tabs v-model="activeName">
        <el-tab-pane label="上传图片" name="first">

          <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8272/upload"
              :on-success="uploadSuccess"
              :show-file-list="false">
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">只能上传 jpg/png 文件，且不超过 500kb</div>
            </template>
          </el-upload>

        </el-tab-pane>
        <el-tab-pane label="图库选择" name="second" lazy>图库选择</el-tab-pane>
      </el-tabs>

    </template>

    <template #footer>
      <span class="dialog-footer">
        <el-button size="small" @click="addImageDialog = false">取 消</el-button>
        <!--        <el-button size="small" type="primary" @click="insertImage">插 入</el-button>-->
      </span>
    </template>
  </el-dialog>

</template>

<script>

import {reactive, toRefs, onMounted, defineComponent} from 'vue';
import {get, post} from "../utils/http";

import {VueUeditorWrap} from 'vue-ueditor-wrap'

import VuePictureCropper, {cropper} from 'vue-picture-cropper'
import {ElMessage} from 'element-plus'

export default defineComponent({
  name: 'Home',
  components: {
    VueUeditorWrap,
    VuePictureCropper,
  },

  setup() {

    const state = reactive({

      activeIndex: 1,

      title: '', // 标题
      desc: '', // 描述
      msg: '',
      pic: '',

      form: {},
      type: 1,
      appId: "",// 小程序appid
      path: "",// 小程序路径
      content: "",// 文字内容

      editor: '',

      options: {
        viewMode: 1,
        dragMode: 'crop',
        aspectRatio: 2.35 / 1,
        // preview: preview,
      },

      activeName: 'first',

      result: '',
      editorConfig: {
        zIndex: 2001,
        initialFrameWidth: 600,
        initialFrameHeight: 600,
        // autoHeightEnabled: false,
        UEDITOR_HOME_URL: '/UEditor/', // 访问 UEditor 静态资源的根路径，可参考常见问题1
        // serverUrl: '//ueditor.szcloudplus.com/cos', // 服务端接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        serverUrl: '',
        toolbars: [
          ['fullscreen', 'source', '|', 'undo', 'redo', '|', 'fontsize', '|', 'blockquote', 'horizontal', '|', 'removeformat', 'cleardoc', 'formatmatch', '|', 'link', 'unlink', 'emotion', '|',
          ],
          [
            'bold', 'italic', 'underline', 'strikethrough', 'fontborder', 'superscript', 'subscript', '|', 'forecolor', 'backcolor', '|', 'indent', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'insertorderedlist', 'insertunorderedlist', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter',
          ],
          [
            'image', 'insertvideo', 'music', 'applets',
          ],
        ],
        labelMap: {
          'applets': '小程序'
        },
      },

      //小程序弹窗
      dialogVisible: false,
      // 图片裁剪区域
      isShowDialog: false,
      addImageDialog: false,

      /**
       *
       */
      onEditorReady(editor) {
        state.editor = editor;
      },
      /**
       * 选中图片
       * @param e
       */
      beforeUpload(e) {
        const file = e.raw;
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          // 更新裁切弹窗的图片源
          // console.log(reader.result);
          state.pic = String(reader.result);
          // 显示裁切弹窗
          state.isShowDialog = true;
        };
      },

      /**
       * 获取base64图片
       * @param imgUrl
       */
      getBase64(imgUrl) {
        let xhr = new XMLHttpRequest();
        xhr.open("get", imgUrl, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          if (this.status == 200) {
            //得到一个blob对象
            let blob = this.response;
            let oFileReader = new FileReader();
            oFileReader.onload = () => {
              state.pic = String(oFileReader.result);
              // 显示裁切弹窗
              state.isShowDialog = true;
            }
            oFileReader.readAsDataURL(blob);
          }
        }
        xhr.send();
      },

      GET() {
        get('/index').then(res => {
          console.log(res);
        })
      },

      /**
       * 保存到本地
       */
      saveToLocal() {
        console.log('111');
      },

      /**
       * 保存并群发
       */
      massMailing() {
        console.log('群发');
      },

      /**
       * 预览
       */
      preview() {

        if (!state.result) {
          ElMessage.warning({
            message: '请选择封面',
            type: 'warning'
          });
          return;
        }
        if (!state.title) {
          ElMessage.warning({
            message: '标题不能为空',
            type: 'warning'
          });
          return;
        }
        post('/upload_thumb', {
          base: state.result
        }).then(res => {
          console.log(res);
          if (res.data.code === 200) {
            post('/preview', {
              title: state.title,
              content: state.msg,
              thumb_media_id: res.data.data['media_id'] || res.data.data['thumb_media_id'],
              desc: state.desc,//简介
            }).then(res => {
              console.log(res);
            })
          }
        })

      },

      /**
       * 清空
       */
      clear() {
        cropper.clear();
      },
      /**
       * 重置
       */
      reset() {
        cropper.reset();
      },

      //
      ready() {
        console.log('111');
      },

      /**
       *  获取裁剪结果
       */
      getResult() {
        // 获取生成的base64图片地址
        const base64 = cropper.getDataURL();
        // 获取生成的blob文件信息
        // const blob = cropper.getBlob();
        // console.log({base64, blob});
        // 把base64赋给结果展示区
        state.result = base64;
        // 隐藏裁切弹窗
        state.isShowDialog = false;
      },

      /**
       * 小程序插入
       */
      insertApplets() {
        console.log('小程序');
        state.dialogVisible = false;
        let str = '';
        if (state.type === 1) {
          str = `<p><a data-miniprogram-appid="${state.appId}" data-miniprogram-path="${state.path}" href="">${state.content}</a></p>`;
        } else if (state.type === 2) {
          str = `<p><a data-miniprogram-appid="${state.appId}" data-miniprogram-path="${state.path}" href=""><img src="https://mmbiz.qpic.cn/mmbiz_jpg/demo/0?wx_fmt=jpg" alt="" data-width="null" data-ratio="NaN"></a></p>`;
        }
        console.log(str);
        state.editor && state.editor.execCommand('inserthtml', str);
        state.content = '';
        state.type = 1;
        state.appId = '';
        state.path = '';
      },

      /**
       * 显示添加窗口
       */
      showDialog(type = 1) {
        console.log(type);
        if (type === 1) {
          state.dialogVisible = true;
        } else if (type === 2) {
          state.addImageDialog = true;
        }
      },

      /**
       * 插入图片
       */
      insertImage() {
        console.log('插入图片');
      },

      /**
       * 图片上传成功回调
       */
      uploadSuccess(res) {
        console.log(res);
        if (res.code === 200) {
          state.addImageDialog = false;
          let str = `<img src="${res.data}" style="width: 100%;" />`
          state.editor && state.editor.execCommand('inserthtml', str);
        }
      },

    });

    onMounted(() => {
      window.customEvent = function (type = 1) {
        state.showDialog(type);
      }
    })

    return {
      ...toRefs(state)
    }
  }

})
</script>
<style lang="scss">
@import "home";

.edui-toolbar {
  background: #fff !important;
}

.edui-box {
  transform: scale(0.9);
}


</style>
